<?php

namespace App\Http\Middleware;

use App\Http\Controllers\Admin\Traits\AdminTrait;
use Closure, Auth,Response;
use App\Models\Admin\AdminMenu;
use App\Utils\RequestUtils;
use Illuminate\Support\Facades\DB;

class AdminPermission
{
    use AdminTrait;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //根据请求获取controller、action
        $restfulParams = RequestUtils::toRestfulParams();

        //公共展示页面
        if(strtolower($restfulParams['class_name']) == 'indexcontroller') {
            return $next($request);
        }
        //管理员认证信息
        $users = Auth::guard('admin')->user();
        //菜单ID
        $menu_id = AdminMenu::where(['controller'=>strtolower($restfulParams['class_name']),'action'=>strtolower($restfulParams['class_method'])])->value('id');
        if(empty($menu_id)){
            return $next($request);
        }

        //超级管理员
        if($users->role_id == 1) {
            return $next($request);
        }

        //验证其他管理员权限
        $count = DB::table('admin_cdj_auth')->where([['role_id',$users->role_id],['menu_id',$menu_id]])->count();
        if(empty($count)){
            return $this->error(['-1',"抱歉，您没有权限"]);
        }
        return $next($request);
    }

    /**
     * 操作返回状态
     * @return json or viem
     */
    protected function result($request,$msg){
        if($request->ajax()){
            return response()->json([
                'code' => 1,
                'msg' => $msg
            ]);
        }else{
            return Response::view('remind', ['code'=>1,'msg' => $msg,'second'=>5], 403);
        }
    }



}
